package com.sinosoft.cnmuseum.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
	
	
	/**      
	 * getDateFileBySuffix(获取转换后的文件存储路径) 
	 * @author wangli
	 * @param filename(xxxxxxxxx.doc xxxxxxx.xls ...) 
	 * @return newfilepath（yyyy/MM/dd/date.getlong().xxx） 
	*/
	public static String getDateFileByFileName(String filename){
		int pos = filename.lastIndexOf(".");
		String suffix = "";
		if(pos > 0){
			suffix = filename.substring(pos);
		}
        Date date = new Date();
        long filenamenew = date.getTime();
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = s.format(date);
        String year = datestr.substring(0, 4);
        String month = datestr.substring(5, 7);
        String day = datestr.substring(8, 10);
        // 2018/04/25/252525252525255252.xxx
        String newfilepath = year + File.separator 
        					+ month + File.separator 
        					+ day + File.separator 
        					+ filenamenew + suffix;
        return newfilepath;
	}
	
	
	/**      
	 * getFileSuffix(获取文件后缀) 
	 * @author wangli
	 * @param filename
	 * @return          
	*/
	public static String getFileSuffix(String filename){
		String suffix = filename.substring(filename.lastIndexOf(".")+1);
		return suffix;
	}
	
	
	/**      
	 * getUpladFilePathByRelativePath(根据相对路径返回上传源文件绝对路径) 
	 * @author wangli
	 * @param relativePath
	 * @return          
	*/
	public static String getUpladFilePathByRelativePath(String relativePath){
		String filepath = ConfigUtil.getProperty(ConfigUtil.UPLOADPATH) + File.separator + relativePath;
		createFileAndPath(filepath);
		return filepath;
	}
	
	
	
	public static void createFileAndPath(String filepath){
		File file = new File(filepath);
		if(!file.exists()){
			File parentfile = file.getParentFile();
			if(!parentfile.exists()){
				//先创建文件夹
				parentfile.mkdirs();
			}
            try {
            	// 创建新文件
            	file.createNewFile();
           } catch (IOException e) {
               System.out.println("创建新文件时出现了错误。。。");
               e.printStackTrace();
           }
		}
	}

}
